import requests,json,zmq,flask

context = zmq.Context.instance()
sock = context.socket(zmq.SUB)
sock.connect('tcp://0.0.0.0:9050')
sock.setsockopt(zmq.SUBSCRIBE, "")

STATUS={}

def update():
  global v
  while  True:
    print 'update'
    res=json.loads(sock.recv())
    # print res
    down=0
    up=0
    for i in res['online_host']:
      for j,v in i.items():
        # print '{ip} {hostname:<30} {down_speed:<5}/{up_speed:<5}'.format(**v)
        down+=int(v['down_speed'])
        up+=int(v['up_speed'])
    STATUS['down']=down
    STATUS['up']=up
    print STATUS
  # break

app=flask.Flask(__name__)

@app.route('/status')
def status():
  resp = flask.Response(json.dumps(STATUS))
  resp.headers['Access-Control-Allow-Origin'] = '*'
  return resp


from thread import start_new_thread
start_new_thread(update,())
# update()


app.run(debug=True)